/**
 * <pre>
 * Title: 		DomainObjectEditor.java
 * Author:		linriqing
 * Create:	 	2010-8-6 上午11:39:35
 * Copyright: 	Copyright (c) 2010
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfinoss.domain;

import java.beans.PropertyEditorSupport;

import org.springframework.beans.SimpleTypeConverter;

import com.hengpeng.common.persist.entity.AbstractEntity;
import com.hengpeng.itfinoss.service.ServiceFactory;

/**
 * <pre>
 * 领域模型对象转换器
 * </pre>
 * @author linriqing
 * @version 1.0, 2010-8-6
 */
public class PersistObjectEditor extends PropertyEditorSupport
{
	private ServiceFactory serviceFactory;

	private SimpleTypeConverter typeConverter = new SimpleTypeConverter();

	private Class<? extends AbstractEntity> type;

	public PersistObjectEditor(Class<? extends AbstractEntity> type, ServiceFactory serviceFactory)
	{
		this.serviceFactory = serviceFactory;
		this.type = type;
	}

	@Override
	public String getAsText()
	{
		Object obj = getValue();
		if (obj == null)
		{
			return null;
		}

		if (obj instanceof AbstractEntity)
		{
			AbstractEntity domainObject = (AbstractEntity) obj;

			return typeConverter.convertIfNecessary(domainObject.getId(), String.class);
		}

		throw new IllegalArgumentException("Value must be a DomainObject");
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException
	{
		if (text == null || 0 == text.length())
		{
			setValue(null);
		}
		else
		{
			AbstractEntity value = serviceFactory.getPersistService().get(type,
					typeConverter.convertIfNecessary(text, Object.class));
			System.out.println("Looking up entity for id " + text + ": " + value);
			setValue(value);
		}
	}

}
